# coding: utf-8
'''
Description: 
version: 1.0.0
Author: peng2.zhang
Date: 2021-08-27 10:29:01
LastEditors: peng2.zhang
LastEditTime: 2021-12-09 17:31:55
'''
from __future__ import division
import ujson
import requests
from ci_conclude.const import CODE
from ci_conclude.base import BaseConclude


class AllureConclude(BaseConclude):

    def get_url(self):
        return self.allure_result_url

    def get_result(self, allure_json_path):
        if not hasattr(self, "_json_result_cache"):
            if allure_json_path.startswith("http"):
                res = requests.get(allure_json_path)
                if res.status_code == 200 and res.ok:
                    json_result = res.json()
                else:
                    return {}
            else:
                with open(allure_json_path) as f:
                    json_result = ujson.load(f)
            if "report" in json_result:
                summary = json_result["report"]["summary"]
                total = summary.get('num_tests', 0)
                passed = summary.get('passed', 0)
                failed = summary.get('failed', 0)
                error = summary.get('error', 0)
                skipped = summary.get('skipped', 0)
                broken = summary.get('broken', 0)
            elif "reportName" in json_result:
                statistic = json_result["statistic"]
                total = statistic.get('total', 0)
                passed = statistic.get('passed', 0)
                failed = statistic.get('failed', 0)
                error = statistic.get('error', 0)
                skipped = statistic.get('skipped', 0)
                broken = statistic.get('broken', 0)
            print(f"total: {total}")
            print(f"failed: {failed}")
            print(f"error: {error}")
            print(f"passed: {passed}")
            print(f"skipped: {skipped}")
            print(f"broken: {broken}")
            # 计算 通过率 pass rate
            if total > 0:
                pass_rate = int(passed) / int(total)
                if pass_rate >= 1:
                    pass_rate = 1                
            else:
                pass_rate = 0
            pass_rate_str = f"{pass_rate:.1f}%"
            # 统计 执行率 exec rate
            if total > 0:
                exec_rate = (int(total) - int(skipped)) / int(total)
                if exec_rate >= 1:
                    exec_rate = 1
            else:
                exec_rate = 0
            exec_rate_str = f"{exec_rate:.1f}%"
            data = {
                "total": total,
                "failed": failed,
                "error": error,
                "passed": passed,
                "skipped": skipped,
                "broken": broken,
                "pass_rate": pass_rate,
                "exec_rate": exec_rate,
            }
            print(data)
            if total == passed:
                _json_result_cache = dict(code=CODE.PASS.ID, message=CODE.PASS.NAME)
            else:
                _json_result_cache = dict(code=CODE.FAIL.ID, message=CODE.FAIL.NAME)
            _json_result_cache.update(dict(data=data, prefix="allure"))
            # from code import interact
            # interact(local=locals())
            setattr(self, "_json_result_cache", _json_result_cache)
        return self._json_result_cache
    
    def format_to_weixin(self, result_kwargs, url):
        """
            result_kwargs: {'code': -1, 'message': 'FAIL', 
                    'data': {
                            'total': 3, 
                            'failed': 1, 
                            'error': 0, 
                            'passed': 2, 
                            'skipped': 0, 
                            'broken': 0, 
                            'pass_rate': '66.67%', 
                            'exec_rate': '100%'}}
            url: https://ci.ecarx.com.cn/view/stdci/job/std-data-collect-service-app-meta/11/allure/
        """
        # title = f"#【{self.project_name}】pipeline #{self.buildid} [stage: {self.stage_name}] 统计结果"
        if result_kwargs:
            content = (f"""\n ## [{self.stage_name} Report] [{result_kwargs["message"]}] [报告地址]({url}) """
                    #f"""\n > [case总数]: <font color="comment">{result_kwargs["data"]["total"]}</font> """
                    f"""\n > [case总数]: <font color="comment">{result_kwargs["data"]["passed"] + result_kwargs["data"]["failed"]}</font> """
                    f"""\n > [case通过数]: <font color="info">{result_kwargs["data"]["passed"]}</font> """
                    #f"""\n > [跳过数]: <font color="comment">{result_kwargs["data"]["skipped"]}</font> """
                    #f"""\n > [缺陷数]: <font color="{'comment' if result_kwargs["data"]["broken"] == 0 else 'warning'}">{result_kwargs["data"]["broken"]}</font> """
                    #f"""\n > [错误数]: <font color="{'comment' if result_kwargs["data"]["error"] == 0 else 'warning'}">{result_kwargs["data"]["error"]}</font> """
                    f"""\n > [case失败数]: <font color="{'comment' if result_kwargs["data"]["failed"] == 0 else 'warning'}">{result_kwargs["data"]["failed"]}</font> """
                    #f"""\n > [通过率]: <font color="info">{f'{result_kwargs["data"]["pass_rate"]*100:.1f}%'}</font> """
                    #f"""\n > [执行率]: <font color="info">{f'{result_kwargs["data"]["exec_rate"]*100:.1f}%'}</font> """
                    )
        else:
            content = f"""\n ## [{self.stage_name} Report] \n <font color="warning">暂无数据</font>"""
        return content
